package com.numberone.master.modules.sys.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.numberone.master.common.utils.DateUtils;
import com.numberone.master.common.utils.DoubleUtil;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.web.BaseController;
import com.numberone.master.common.yunzhanghu.TixianUtil;
import com.numberone.master.modules.news.service.NewsService;
import com.numberone.master.modules.orders.entity.WithdrawalsOrder;
import com.numberone.master.modules.orders.service.ShareOrderService;
import com.numberone.master.modules.orders.service.WithdrawalsOrderService;
import com.numberone.master.modules.profit.dao.AccountInfoDao;
import com.numberone.master.modules.profit.entity.AccountInfo;
import com.numberone.master.modules.profit.service.AccountInfoService;
import com.numberone.master.modules.sys.entity.NoticeInfo;
import com.numberone.master.modules.sys.entity.Office;
import com.numberone.master.modules.sys.entity.User;
import com.numberone.master.modules.sys.service.NoticeInfoService;
import com.numberone.master.modules.sys.service.OfficeService;
import com.numberone.master.modules.sys.utils.UserUtils;

/**
 * Author: ck
 * <p>首页信息
 * Date: Created in 2017/7/5 10:15
 */
@Controller
@RequestMapping(value = "${adminPath}/home/")
public class IndexController extends BaseController{

	@Autowired
	private NewsService newsService;
	@Autowired
	private AccountInfoDao accountInfoDao;
	@Autowired
	private NoticeInfoService noticeInfoService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private AccountInfoService accountInfoService;
	@Autowired
	private ShareOrderService shareOrderService;
	@Autowired
	private WithdrawalsOrderService withdrawalsOrderService;
	
	/**
	 * 打开首页
	 * @return
	 */
    @RequestMapping(value = {"index"})
    public String openIndex(Model model){
    	String id = UserUtils.getUser().getOffice().getId();
    	//查询个人信息
    	model.addAttribute("password", UserUtils.get(UserUtils.getUser().getId()).getPassword());
    	model.addAttribute("id", id);
    	model.addAttribute("userId", UserUtils.getUser().getId());
    	model.addAttribute("office", officeService.get(id));
    	model.addAttribute("user", UserUtils.getUser());

    	//消息信息
    	int unread = newsService.getCount(id,"0");//未读消息
    	model.addAttribute("unread", unread);
    	int read = newsService.getCount(id,"1");//已读消息
    	model.addAttribute("read", read);
    	//账户余额
    	AccountInfo account = accountInfoDao.getBalance(id);
    	model.addAttribute("kamt", account.getKamt());
    	//已提现和到账金额
    	Double taskMoney = accountInfoDao.getTaskMoney(id);
    	BigDecimal b = new BigDecimal(taskMoney);
    	model.addAttribute("taskMoney", b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
    	Double arrivalMoney = accountInfoDao.getArrivalMoney(id);
    	BigDecimal a = new BigDecimal(arrivalMoney);
    	model.addAttribute("arrivalMoney", a.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
    	//公告
    	NoticeInfo noticeInfo = new NoticeInfo();
    	noticeInfo.setDelFlag("0");
    	List<NoticeInfo> noticeList = noticeInfoService.findList(noticeInfo);
    	model.addAttribute("notList", noticeList);
    	//查询过去时间
    	List<String> dateList = DateUtils.getPastDateList(7);
    	List<String> list = new ArrayList<>();
    	List<String> weekDateList = new ArrayList<>();
		for (int i = 6; i != -1; i--) {
			String date = dateList.get(i);
			list.add(date);//时间
			//根据时间查询
			Double price = shareOrderService.getPriceByDate(date, id);
			weekDateList.add(String.valueOf(price));
		}
    	model.addAttribute("dateList", list.toString().replace("[", "").replace("]", ""));
    	model.addAttribute("weekDateList", weekDateList.toString().replace("[", "").replace("]", ""));
        return "modules/home/index";
    }
    
    /**
     * 账户充值
     * @param user
     * @param redirectAttributes
     * @return
     */
	@RequiresPermissions("sys:user:recharge")
	@RequestMapping(value = "recharge")
	public String recharge(User user, RedirectAttributes redirectAttributes) {
		String officeId = UserUtils.getUser().getOffice().getId();
		if(StringUtils.equals(officeId, "1")){
			addMessage(redirectAttributes, "管理员禁止充值！");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		addMessage(redirectAttributes, "充值功能待开发中！");
		return "redirect:" + adminPath + "/home/index?repage";
	}
	
	/**
	 * 账户提现
	 * @param taskMoney
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:task")
	@RequestMapping(value = "task")
	public String task(String taskMoney, RedirectAttributes redirectAttributes) {
		User user=UserUtils.getUser();
		String officeId =user.getOffice().getId();
		Office office = officeService.get(officeId);
		if(office == null){
			addMessage(redirectAttributes, "未查询到提现的账户信息！");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		
		AccountInfo accountInfo = accountInfoService.getAccountByOfficeId(officeId);
		if(accountInfo == null){
			addMessage(redirectAttributes, "未查询到提现的账户信息！");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		if(!StringUtils.equals(officeId, office.getId())){
            addMessage(redirectAttributes, "当前登录与提钱账户不符合，提现失败。！");
            return "redirect:" + adminPath + "/home/index?repage";
        }
        String kamt = accountInfo.getKamt();

        if(StringUtils.isEmpty(kamt)){
			addMessage(redirectAttributes, "本机构可提现余额不足，提现失败。");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		Double price = new Double(taskMoney);
		if(Double.doubleToLongBits(price) <= Double.doubleToLongBits(2)){
			addMessage(redirectAttributes, "提现金额必须大于2元，提现失败。");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		if(new BigDecimal(kamt).compareTo(new BigDecimal(taskMoney))<0){
			addMessage(redirectAttributes, "提现金额大于可提现余额，提现失败。");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		String acct_no = office.getCardNo();     //银行卡号
		String acct_name = office.getCardName(); //提现人姓名
		if(StringUtils.isEmpty(acct_no) || StringUtils.isEmpty(acct_name)){
			addMessage(redirectAttributes, "本机构的卡号为空,无法提现，提现失败。");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		String identity = user.getIdentity();    //身份证号码
		if (StringUtils.isEmpty(identity)) {
			addMessage(redirectAttributes, "您的信息填写不完全,无法提现，请补全个人信息。");
			return "redirect:" + adminPath + "/home/index?repage";	
		}	
		if(StringUtils.isEmpty(acct_name)){
			addMessage(redirectAttributes, "本机构的持卡人为空,无法提现，提现失败。");
			return "redirect:" + adminPath + "/home/index?repage";
		}
		//存入订单号
		String orderNo = "WLWK-"+StringUtils.getDateString(5);
		//扣除手续费
		Double money = DoubleUtil.sub(Double.valueOf(taskMoney), new Double(2));
		try {
			//先查看云账户是否余额充足
			TixianUtil.queryAccountAmount(String.valueOf(money));

			//LianLianPay.payment(orderNo, StringUtils.getDateString(0),String.valueOf(money), acct_no, acct_name, "物联网卡提现", "0", "http://121.196.210.134:8082/wlwks/project/wlwk/resultNotification", "物联网卡提现");

			//2019.03.06 云账户提现
			TixianUtil.TiXian(orderNo,acct_name,acct_no,identity,String.valueOf(money),"云账户提现");
		} catch (Exception e) {
			addMessage(redirectAttributes, e.getMessage());
			return "redirect:" + adminPath + "/home/index?repage";
		}
		//添加订单流水
		WithdrawalsOrder order = new WithdrawalsOrder();
		order.setWithdrwalsAmount(taskMoney);//提现金额
		order.setCreateById(officeId);
		order.setCreateDate(new Date());
		order.setRemarks("物联网提现");
		order.setArrivalAmount(String.valueOf(money));//到账金额
		order.setOrderNo(orderNo);
		order.setState("1");
		order.setOfficeId(officeId);
		withdrawalsOrderService.insert(order);
		//个人账户减提现金额
		Double memory = Double.valueOf(taskMoney);
		Double kamtMoney = Double.valueOf(accountInfo.getKamt());
		Double damt = Double.valueOf(accountInfo.getDamt());
		accountInfo.setDamt(String.valueOf(DoubleUtil.add(damt, memory)));
		accountInfo.setKamt(String.valueOf(DoubleUtil.sub(kamtMoney, memory)));
		accountInfoService.update(accountInfo);
		addMessage(redirectAttributes, "提现成功，请等待审核。");
		return "redirect:" + adminPath + "/home/index?repage";
	}
	
}
